<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/common/common.jsp"%>
<%@ page import="com.cinsea.common.OptType"%>
<%@ page import="com.cinsea.directory.model.Directory"%>
<%@ page import="com.cinsea.directory.service.DirectoryService"%>
<%@ page import="com.cinsea.util.StringUtil"%>
<%@ page import="java.net.URLEncoder"%>
<%@ page import="java.util.Enumeration"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>
<%@ page import="com.cinsea.pageextend.service.PageextendService" %>
<%@ page import="com.cinsea.log.model.Log" %>
<%@ page import="com.cinsea.log.service.LogService" %>
<%@ page import="com.cinsea.form.model.*" %>
<%@ page import="com.cinsea.workflow.service.*" %>
<%@ page import="com.cinsea.form.service.*" %>
<%@ page import="com.cinsea.security.service.RightService" %>
<%@ page import="com.alibaba.fastjson.JSON" %>


<%	int pagesize=20;
	//工作流的所有参数列表
    response.setHeader("cache-control", "no-cache");
    response.setHeader("pragma", "no-cache");
    response.setHeader("expires", "Mon 1 Jan 1990 00:00:00 GMT");
	Map workflowparameters = new HashMap();

    String directoryid = StringUtil.null2String(request.getParameter("directoryid")).trim();
	String id = StringUtil.null2String(request.getParameter("processid")).trim();
	String nodeid = StringUtil.null2String(request.getParameter("nodeid")).trim();
    FormprocessService formprocessServiceice =(FormprocessService) Env.getBean("formprocessService");
    if(StringUtil.isEmpty(id) && StringUtil.isEmpty(directoryid)){
		%>
		<SCRIPT LANGUAGE="JavaScript">
			pop('dowid字段未接收参数，请联系系统管理员。');
			var tabpanel=top.contentPanel;
			tabpanel.remove(tabpanel.getActiveTab());
		</SCRIPT>
		<%
		return;
	}
    if(StringUtil.isEmpty(directoryid)){
        directoryid = formprocessServiceice.get(id).getDowid();
    }

	if(id.equals("del")){
		%>
		<SCRIPT LANGUAGE="JavaScript">
			pop('删除成功！');
			var tabpanel=top.contentPanel;
			tabpanel.remove(tabpanel.getActiveTab());
		</SCRIPT>
		<%
		return;
	}

    FormdataService fs = (FormdataService) Env.getBean("formdataService");
    FormviewService formviewService= (FormviewService) Env.getBean("formviewService");
    FormprocessService fbs = (FormprocessService) Env.getBean("formprocessService");
    DirectoryService cs = (DirectoryService) Env.getBean("directoryService");
	FormviewService fls = (FormviewService) Env.getBean("formviewService");
	Directory directory = cs.getDirectoryById(directoryid);
    FormService formService=(FormService) Env.getBean("formService");
    RightService rightService = (RightService) Env.getBean("rightService");
	String msg = StringUtil.null2String(request.getParameter("msg")).trim();
    Form form=formService.getFormById(directory.getPFormid());
    Env.setDowid(directoryid);
    Env.setTablename(form.getTablename());

	workflowparameters.put("dowid", directoryid);
	workflowparameters.put("processid",id);
	workflowparameters.put("nodeid",nodeid);

	String becreate = "1"; //是否新建表单
	if(!StringUtil.isEmpty(id)){
		becreate = "0";
        Formprocess formprocess= fbs.get(id);
        if(formprocess.getDeleted().intValue()==1){
			response.sendRedirect(request.getContextPath()+"/nodata.jsp");
			return;
		}
        if(StringUtil.isEmpty(directoryid)){
        directoryid =formprocess.getDowid();
        directory =cs.getDirectoryById(directoryid);
        }
    }
	workflowparameters.put("becreate",becreate);
    String initparameterstr=null;
    Map jsonObject=new HashMap();
    Map initparameters = new HashMap();
	for( Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
		String pName = e.nextElement().toString().trim();
		String pValue = StringUtil.trimToNull(request.getParameter(pName));
		if(!StringUtil.isEmpty(pName)){
			initparameters.put(pName,pValue);
            if(!StringUtil.isEmpty(pValue))
            jsonObject.put(pName,pValue);

        }
    }
    initparameterstr= JSON.toJSONString(jsonObject);
	workflowparameters.put("initparameters",initparameters);
	//处理输入参数完成

	workflowparameters.put("formviewtype","1");

	String onlyread = "0";
	String editmode = StringUtil.null2String(request.getParameter("editmode"));
	if(StringUtil.isEmpty(editmode))
		editmode = "0";

	if(becreate.equals("1")){
		boolean isauth = rightService.checkOpttype(directoryid, 2);
		if(!isauth){
			response.sendRedirect(request.getContextPath()+"/nopermit.jsp");
			return;
		}
        workflowparameters.put("formviewtype","2");
    }

	int righttype = 0;
	String objid = id;
	String tablename = form.getTablename();

	if (!StringUtil.isEmpty(objid)) {
        boolean opttype = rightService.checkOpttype(id, OptType.VIEW);
        if (!opttype) {
            response.sendRedirect(request.getContextPath()+"/nopermit.jsp");
            return;
        }
        righttype = rightService.getOpttype(objid);
	}



	int canedit = 0;
    if(righttype%15 == 0){
		canedit = 1;
	}
	if(editmode.equals("1")&&canedit!=1){
			response.sendRedirect(request.getContextPath()+"/nopermit.jsp");
			return;
	}

	if(editmode.equals("1")&&canedit==1){
        workflowparameters.put("formviewtype","2");
        onlyread = "0";
    }




    workflowparameters.put("onlyread",onlyread);
	workflowparameters.put("processtype","2");
    String formid="";
    if( directory.getPFormid()!=null && !"".equals(directory.getPFormid())){
        formid= directory.getPFormid();
        workflowparameters.put("formid",formid);
    }
	String viewid="";
    int notifyclose=0;
    if(becreate.equals("1")){
        List layoutlist = fls.getOptLayoutList(directory.getId(), OptType.CREATE);
        for (Object layout : layoutlist) {
            if(StringUtil.isEmpty((String)layout))
            continue;
            if (fls.getFormviewById((String) layout).getTypeid() == 2){
                viewid = fls.getFormviewById((String) layout).getId();
                break;
            }
        }
        if (StringUtil.isEmpty(viewid))
            viewid = directory.getPCreateviewid();
        workflowparameters.put("viewid",viewid);
         notifyclose=1;
    }else if(editmode.equals("1")){
		List layoutlist = fls.getOptLayoutList(id,OptType.MODIFY);
		for (Object layout : layoutlist) {
            if(StringUtil.isEmpty((String)layout))
            continue;
            if (fls.getFormviewById((String) layout).getTypeid() == 2){
                viewid = fls.getFormviewById((String) layout).getId();
                break;
            }
        }
        if (StringUtil.isEmpty(viewid))
            viewid = directory.getPEditviewid();
        workflowparameters.put("viewid",viewid);
        notifyclose=1;
	}else{
		List layoutlist = fls.getOptLayoutList(id,OptType.VIEW);
		for (Object layout : layoutlist) {
            if(StringUtil.isEmpty((String)layout))
            continue;
            if (fls.getFormviewById((String) layout).getTypeid() == 1){
                viewid = fls.getFormviewById((String) layout).getId();
                break;
            }
        }
        if (StringUtil.isEmpty(viewid))
            viewid = directory.getPReadviewid();
        workflowparameters.put("viewid",viewid);
    }
    workflowparameters = fs.getFormdata(workflowparameters);
    viewid = StringUtil.null2String(workflowparameters.get("viewid"));
	String needcheckfields = StringUtil.null2String(workflowparameters.get("needcheck"));
	String formcontent = StringUtil.null2String(workflowparameters.get("formcontent"));

	
	String fieldcalscript = StringUtil.null2String(workflowparameters.get("fieldcalscript"));
    String onaddrowscript = StringUtil.null2String(workflowparameters.get("onaddrowscript"));
    String triggercalscript= StringUtil.null2String(workflowparameters.get("triggercalscript"));
    String ufscript= StringUtil.null2String(workflowparameters.get("ufscript"));
    String directscript= StringUtil.null2String(workflowparameters.get("directscript"));
    FormfieldService formfieldService = (FormfieldService) Env.getBean("formfieldService");
    String directoryfield ="";
            if (!StringUtil.isEmpty(formid)) {
                List<Formfield> fields = formfieldService.getFieldsByMainformId(formid);
                for(Formfield field:fields){
                    if(field.getFieldname().equalsIgnoreCase("dowid")){
                       directoryfield =""+field.getId();
                        break;
                    }
                }
            }

            //log
            LogService logService = (LogService) Env.getBean("logService");
            request.setAttribute("directory", directory);
            logService.CreateLog(request);


        %>

<%
//页面菜单
String tabStr="";
boolean hasTab=false;

if(becreate.equals("1")||editmode.equals("1")){
	//提交
	pagemenustr +="addBtn(tb,'"+I18n.getTextByPrefix("submit",directoryid)+"','S','accept',function(){onSubmit(2)});";
	//返回
    pagemenustr += "addBtn(tb,'"+I18n.getTextByPrefix("cancel",directoryid)+"','B','arrow_redo',function(){onCancel()});";
}else{
	if(rightService.checkOpttype(id, 15)){
		pagemenustr += "addBtn(tb,'"+I18n.getTextByPrefix("edit",directoryid)+"','M','application_form_edit',function(){onEdit()});";
	}
	if(!StringUtil.isEmpty(directoryid)){
		paravaluehm.put("{id}",id);
		paravaluehm.put("{directoryid}", directoryid);
		paravaluehm.put("tableName", form.getTablename());
		PageextendService _pageextendService2 =(PageextendService) Env.getBean("pageextendService");
        ArrayList<String> menuList= _pageextendService2.getPageextendStrExt(directoryid,paravaluehm);
		pagemenustr += menuList.get(0);
        tabStr += menuList.get(1);
	}


    if(rightService.checkOpttype(id, 75)){
		pagemenustr += "addBtn(tb,'"+I18n.getText("delete")+"','D','delete',function(){onDelete('"+id+"')});";
	}
}
if(!StringUtil.isEmpty(viewid)){
		paravaluehm.put("{id}",id);
		paravaluehm.put("{viewid}",viewid);
		paravaluehm.put("tableName", form.getTablename());
		PageextendService _pageextendService2 =(PageextendService) Env.getBean("pageextendService");
        ArrayList<String> menuList= _pageextendService2.getPageextendStrExt(viewid,paravaluehm);
		pagemenustr += menuList.get(0);
        tabStr += menuList.get(1);
	}
if(!tabStr.equals(""))
hasTab=true;
String reportid= directory.getPReportid();
%>
<html>
  <head>
    <%@include file="/common/head.jsp"%>
<script language="JavaScript" src="${ctx}/chart/bindows_gauges/bindows_gauges.js"></script>
<script language="JavaScript" src="${ctx}/chart/fusionchart/FusionCharts.js"></script>
<script src='${ctx}/dwr/interface/DataService.js'></script>
<script src='${ctx}/dwr/interface/OptionService.js'></script>
<script src='${ctx}/dwr/util.js'></script>
    <style type="text/css">
        .x-panel-body {
            border-bottom: #99bbe8 0px solid;
            position: relative;
            border-left: #99bbe8 0px solid;
            border-right: #99bbe8 0px solid
        }

        .x-panel-body-noheader {
            border-top: #99bbe8 0px solid
        }
    </style>
<script type="text/javascript">
    var needformatted = true;
    var caldelay = 200;
    var daliog1;
    Ext.onReady(function() {
        Ext.QuickTips.init();
        <%if(!pagemenustr.equals("")){%>
       tb = new Ext.Toolbar();
       tb.render('pagemenubar');
       <%=pagemenustr%>
       <%}%>

         var c = new Ext.Panel({
               <%if(hasTab){%>title:'<%=I18n.getText("form")+I18n.getText("info")%>',iconCls:Ext.ux.iconMgr.getIcon('application'),<%}else{%>region:'center',<%}%>
               layout: 'border',
               <%if(!pagemenustr.equals("")){%>
               items: [{region:'north',items:[tb],height:26},{region:'center',autoScroll:true,contentEl:'divsum'}]
              <%}else{%>
             items: [{region:'center',autoScroll:true,contentEl:'divsum'}]

             <%}%>
           });
     <%if(hasTab){%>
     var contentPanel = new Ext.TabPanel({
            region:'center',
            id:'formtabPanel',
            deferredRender:false,
            enableTabScroll:true,
            autoScroll:true,
            activeTab:0,
            items:[c]
        });
       <%=tabStr%>
       <%}%>
     //ie6 bug

      //Viewport
	viewport = new Ext.Viewport({
        layout: 'border',
        items: [<%if(hasTab){%>contentPanel<%}else{%>c<%}%>]
	});
    Ext.get('divsum').setVisible(true);
             daliog0 = new Ext.Window({
                         layout:'border',
                         closeAction:'hide',
                         plain: true,
                         modal :true,
                         width:viewport.getSize().width*0.5,
                         height:viewport.getSize().height*0.42,
                         buttons: [{
                             text     : '<%=I18n.getText("close")%>',
                             handler  : function(){
                                 daliog0.hide();
                             }

                         }],
                         items:[{
                         id:'dlgpanel',
                         region:'center',
                         xtype     :'iframepanel',
                         frameConfig: {
                             autoCreate:{id:'dlgframe', name:'dlgframe', frameborder:0} ,
                             eventsFollowFrameLinks : false
                         },
                         autoScroll:true
                     }]
                     });

             daliog1 = new Ext.Window({
                         layout:'border',
                         closeAction:'hide',
                         plain: true,
                         modal :true,
                         width:viewport.getSize().width*0.75,
                         height:viewport.getSize().height*0.8,
                         buttons: [{
                             text     : '<%=I18n.getText("close")+"&"+I18n.getText("refresh")%>',
                             handler  : function(){
                                 document.location.reload();
                                 daliog1.hide();
                             }

                         }],
                         items:[{
                         id:'dlgpanel',
                         region:'center',
                         xtype     :'iframepanel',
                         frameConfig: {
                             autoCreate:{id:'dlgframe1', name:'dlgframe1', frameborder:0} ,
                             eventsFollowFrameLinks : false
                         },
                         autoScroll:true
                     }]
                     });
      formatTables();  
    })


var needchecklists = "<%=needcheckfields%>";
var id = "<%=StringUtil.null2String(id)%>";
var dowid = "<%=StringUtil.null2String(directoryid)%>";
var nodeid = "<%=StringUtil.null2String(nodeid)%>";

</script>

<script type="text/javascript">
    function setBrowser(inputname,inputspan,browserid,param,viewurl,isneed){
        id=ReturnValue;
        var fieldfunc=-1;
        if(param)
         fieldfunc=param.indexOf("function:");
        if (id!=null) {
    if (id[0] != '0') {
        document.getElementById(inputname).value = id[0];
        if(!Ext.isIE) $('#'+inputname).trigger("AttrModified");
		document.getElementById(inputspan).innerHTML = id[1];
          if(fieldfunc>-1){
          funcname=param.substring(9);
      scripts="valid="+funcname+"('"+id[0]+"');";
        eval(scripts) ;
        if(!valid){  //valid默认的返回true;
         document.getElementById(inputname).value = '';
		if (isneed=='0')
		document.getElementById(inputspan).innerHTML = '';
		else
		document.getElementById(inputspan).innerHTML = '<img src=${ctx}/images/base/checkinput.gif>';
          }
          }
    }else{
		document.getElementById(inputname).value = '';
        if(!Ext.isIE) $('#'+inputname).trigger("AttrModified");
		if (isneed=='0')
		document.getElementById(inputspan).innerHTML = '';
		else
		document.getElementById(inputspan).innerHTML = '<img src=${ctx}/images/base/checkinput.gif>';

            }
         }
    }
    function getBrowser(inputname,inputspan,browserid,param,viewurl,isneed){
        var fieldfunc=-1;
        if(param)
          fieldfunc=param.indexOf("function:");
        if(fieldfunc>-1){}else{
            var param = parserRefParam(inputname,param);
        }
	var idsin = document.getElementsByName(inputname)[0].value;
	var id;
    try{
         var url ='${ctx}/browser/browser.jsp?id='+browserid+'&'+param+'&idsin='+idsin
            if (idsin.length > 900) {   //当idsin过长时，ie的url不支持过长的地址
                url ='${ctx}/browser/browser.jsp?id='+browserid+'&'+param;
            }
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))|| (navigator.userAgent.match(/iPad/i))|| (navigator.userAgent.match(/Android/i)))
    id=showDialog(url,null,null,function(){
        setBrowser(inputname,inputspan,browserid,param,viewurl,isneed) ;
    });
    else
    id=showDialog(url);
    }catch(e){return}
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))|| (navigator.userAgent.match(/iPad/i))|| (navigator.userAgent.match(/Android/i)))
    ;
    else
    setBrowser(inputname,inputspan,browserid,param,viewurl,isneed);

    }
    function  addBrowser(inputname,inputspan,doctype,viewurl,isneed,docdir){
        params = ""
        targeturl = "<%=URLEncoder.encode("/common/closedialog.jsp", "UTF-8")%>"
        var id;
        try{
            id = showDialog("${ctx}/document/documentcreate.jsp?directoryid="+docdir+"&doctype="+doctype+params+"&targeturl="+targeturl,"dialogHeight:"+screen.availHeight+"px;dialogWidth:"+screen.availWidth+"px; center: Yes; help: No; resizable: yes; status: No");

        }catch(e){return}
          if (id!=null) {

    if (id[0] != '0') {
		document.getElementById(inputname).value = id[0];
		document.getElementById(inputspan).innerHTML = id[1];
    }else{
		document.getElementById(inputname).value = '';
		if (isneed=='0')
		document.getElementById(inputspan).innerHTML = '';
		else
		document.getElementById(inputspan).innerHTML = '<img src=${ctx}/images/base/checkinput.gif>';

            }
         }
    }
</script>

 
  </head>
  <body onclick="task.delay(caldelay,null,this);">

<div id="divsum" style="display:none;" >
<form action="${ctx}/formdata.do" target="_self" enctype="multipart/form-data"  name="mainForm"  id="mainForm"  method="post" >

    <div id="pagemenubar"></div>
<!--页面菜单结束-->
<%
	if(!StringUtil.isEmpty(msg)){
%>
<DIV><font color=red><%=StringUtil.getDecodeStr(msg)%></font></div>
<%}%>

<input type="hidden" name="action" value="createformdata">
<input type="hidden" name="targeturl">
<input type="hidden" name="dowid" id="dowid" value="<%=directoryid%>">
<input type="hidden" name="formid" id="formid" value="<%=directory.getPFormid()%>">
<input type="hidden" name="viewid" id="viewid" value="<%=viewid%>">
<input type="hidden" name="creator" id="creator" value="<%=Env.getRemoteUser().getCurrentuserid()%>">
<input type="hidden" name="processid" id="processid" value="<%=id%>">
<input type="hidden" name="nodeid" value="<%=nodeid%>">
<input type="hidden" name="submitnew"  id="submitnew" value=""/>

<input type="hidden" name="editmode" value="<%=editmode%>">
<input type="hidden" name="canedit" value="<%=canedit%>">
<input type="hidden" name="currentuserid" value="<%=Env.getRemoteUser().getCurrentuserid()%>">
<input type="hidden" name="becreate" value="<%=becreate%>">
<input type="hidden" name="initparameterstr" value='<%=initparameterstr%>'>
  <input type="hidden" name="notifyclose" id="notifyclose" value='<%=notifyclose%>'>
    <table class=noborder>
				<colgroup>
					<col width="20%">
					<col width="80%">
				</colgroup>

	</table>

<%=formcontent%>
<input type="hidden" name="tmpvalue" id="tmpvalue" value="">


  </form>
  </div>
<div id="dlgdiv" style="display: none">
    <form name="excelForm" id="excelForm" method="post" target="uploadframe" enctype="multipart/form-data">
        <input type="hidden" name="dowids" id="dowids">
        <table style="border:0">
            <colgroup>
                <col width="1%">
                <col width="20%">
                <col width="79%">
            </colgroup>

            <TR>
                <TD class=Spacing colspan=3></TD>
            <TR>
            <TR>
                <TD class=Line colspan=3></TD>
            <TR>
            <TR>
                <TD class=Spacing colspan=3 align="center">请在下面选择需要导入的excel文档</TD>
            <TR>
            <TR>
                <TD class=Line colspan=3></TD>
            <TR>
            <TR>
                <TD colspan=3>&nbsp;</TD>
            <TR>
            <TR>
                <TD colspan=3 align="center"><input type="file" name="path"/></TD>
            <TR>
        </table>
    </form>
    <iframe id="uploadframe" name="uploadframe" src="${ctx}/excel/uploadframe.jsp" width="0" height="0"
            style="top:-100px;"></iframe>

    <div id="progressBarhome">
        <div id="progressBar">
            <div class="status" id="p1text"></div>
            <div id="p1" style="width:300px;display:inline"></div>
            <div id="importMessage">
                导入的记录总数：&nbsp;&nbsp;<span id="totalnum">0</span><br/>
                    <span id="curmsg">当前正导入第 <span id="curnum">0
                    </span> 条记录</span><span id="endmsg" style="display:none">操作完成!</span><br/>
                成功记录数: <span id="successNum">0</span>&nbsp;&nbsp;
                失败记录数: <span id="lostNum">0</span>&nbsp;&nbsp;<br/>
                <a id="successRecord" href="javascript:downloadLostRecord()"></a>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" language="javascript" src="<%= request.getContextPath()%>/datapicker/WdatePicker.js"></script>
  </body>
</html>
  <script language="javascript">
      var tableformatted = false;
      function formatTables() {
          if (needformatted) {
              Ext.each(Ext.query("table[id*='oTable']"), function() {
                  tableformatted = true;
                  formatTable(this);
              });
              Ext.each(Ext.query("table[id*='oTable']"), function() {
                  this.onresize=function(){formatTable(this)};
              });
          }
      }
  var inputid;
  var spanid;
  var temp;
  [].indexOf || (Array.prototype.indexOf = function(v)
{
	for(var i = this.length; i-- && this[i] !== v;);
	return i;
}
);

$(document).ready(function($){
    <%=ufscript%>
    <%=directscript%>
   $.Autocompleter.Selection = function(field, start, end) {
         var flag;
       if(Ext.isIE){
         flag= field.createTextRange; //在firefox下span不显示 原因是因为  firefox不支持createTextRange 
       }else{
         flag=true;
       }
       if(flag){
           if (Ext.isIE) { 
               var selRange = field.createTextRange();
               selRange.collapse(true);
               selRange.moveStart("character", start);
               selRange.moveEnd("character", end);
               selRange.select();
           }
        if(inputid==undefined||spanid==undefined)
           return;
         var len=field.value.indexOf("  ");
           var lenspance=field.value.indexOf(" ");
             if(temp==0&&len>0){
             temp=1;
         var  length=field.value.length;
           var data=field.value;
        document.getElementById(inputid).value=field.value.substring(0,field.value.indexOf("  "));
       document.getElementById(spanid+'span').innerHTML= data.substring(len,length);
         }else if(temp==0&&lenspance>0){

           var data=field.value;
        document.getElementById(inputid).value=data;
       document.getElementById(spanid+'span').innerHTML= data;
             }else
             {
               document.getElementById(inputid).value="";

             }
 } else if( field.setSelectionRange ){
        field.setSelectionRange(start, end);
	} else {
           if( field.selectionStart ){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	}
	field.focus();
};

 });

	var strSQLs = new Array();
	var strValues = new Array();
   <%=triggercalscript%>
 function checkUnique(obj,param,isonly,fieldname,tablename){
    if(obj.value.trim()=='')
    return;
     if(isonly==1||param=="")
     {
        param="select "+fieldname+" from "+tablename+" where "+fieldname+" = ?";
     }
    param=param.replace("?","'"+obj.value.ReplaceAll("'","''")+"'");
   if(SQL(param)!=''){
      alert('数据已存在,请重新输入！') ;
      obj.value='';
      obj.focus();
   }

  }
  function checkdirect(obj)
  {
      inputid=obj.id;
      spanid=obj.name.substring(1);
      temp=0;
  }
  function SQL(param){
				//param = encode(param);

				if(strSQLs.indexOf(param)!=-1){
					var retval = getValidStr(strValues[strSQLs.indexOf(param)]);
					return retval;

				}else{
                    var _url= "${ctx}/data.do";
                    var retval;
                    Ext.Ajax.request({
                        url:_url,
                        sync:true,
                        params:{sql:param},
                        success: function(res) {
                                  var doc=res.responseText;
                            retval = getValidStr(doc);
                            strSQLs.push(param);
                            strValues.push(retval);
                        }
                    });
					return retval;
				}             
			}
  function onCal(){
		try{

			var rowindex = 0;
		<%=fieldcalscript%>


			function SUM(param){
				var result = 0;
				for(index=0;index<rowindex;index++){
					tmpval = 0;
					try{
					tmpval = eval(param)*1;
					}catch(e){
					tmpval = 0;
					}
					//alert(tmpval);
					result += tmpval;
				}
				rowindex = 0;
				return result;
			}

			function RMB(param){
				var tmpval = eval(param)*1;
				var result =  convertCurrency(tmpval);
				return result;
			}
			function COUNT(param){
				var result = 0;
				for(index=0;index<rowindex;index++){
					tmpval = 0;
					try{
					tmpval = eval(param)*1;
					}catch(e){
					tmpval = 0;
					}
					if(tmpval != 0)
						result ++;
				}
				rowindex = 0;
				return result;
			}
			function PROD(param){
				var result = 1;
				for(index=0;index<rowindex;index++){
					tmpval = 1;
					try{
					tmpval = eval(param)*1;
					}catch(e){
					tmpval = 1;
					}
					//alert(tmpval);
					result = result * tmpval;
				}
				rowindex = 0;
				return result;
			}
			function MAX(param){
				var result = 0;
				for(index=0;index<rowindex;index++){
					tmpval = 0;
					try{
					tmpval = eval(param)*1;
					}catch(e){
					tmpval = 0;
					}
					if(tmpval > result)
						result = tmpval;
				}
				rowindex = 0;
				return result;
			}



		}catch(e){}
}
  function onAddRow(){
		try{
            <%=onaddrowscript%>
		}catch(e){}
}

      function formatTable(t) {
          if (t.innerHTML.indexOf('oTable') < 0)
              return;
          var datarow ;
          for (i = 0; i < t.rows.length; i++) {
              tablerow = t.rows[i];
              if (tablerow.cells[0] && tablerow.cells[0].firstChild && tablerow.cells[0].firstChild.id && tablerow.cells[0].firstChild.id.indexOf('oTable') == 0) {
                  datarow = t.rows[i];
              }
          }
          if (datarow == null)
              return;
          var rowheight = new Array();
          tablecount = datarow.cells.length;
          rowcount = datarow.cells[0].firstChild.rows.length;
          equalrowcount=0;
          if (rowcount > 10)
              caldelay = 10000;
          for (i = 0; i < rowcount; i++) {
              equalcount = 0;
              for (j = 0; j < tablecount; j++) {
                  otable = datarow.cells[j].firstChild;
                  orows = otable.rows;
                  if (j > 0 && orows[i].clientHeight == datarow.cells[j - 1].firstChild.rows[i].clientHeight)
                      equalcount++
                  if (!rowheight[i])
                      rowheight[i] = orows[i].clientHeight;
                  else if (rowheight[i] < orows[i].clientHeight)
                      rowheight[i] = orows[i].clientHeight;
              }
              if (equalcount == tablecount - 1){
                  equalrowcount++;
              }
          }
          if(equalrowcount==rowcount)
            return;
          for (i = 0; i < datarow.cells.length; i++) {
              otable = datarow.cells[i].firstChild;
              orows = otable.rows;
              for (j = 0; j < orows.length; j++) {
                  orows[j].cells[0].style.height = rowheight[j];
              }
          }
      }
onAddRow();
if (Ext.isIE) {
         inputs = document.mainForm.getElementsByTagName("input");
         for (i = 0; i < inputs.length; i++) {
             inputel = inputs[i];
             if (inputel.value && inputel.value != '')
                 inputel.fireEvent('onpropertychange');
         }
     }else{
         $('input').trigger("AttrModified");
     }
var task=new Ext.util.DelayedTask(onCal);
</script>

<script language="javascript">
    //jsmap
    var objectKey = new Array(100);
    var objectValue = new Array(100);
    var timevalue = "";
    function getMapValue(key){
        for(var i=0;i<objectKey.length;i++){
            if(objectKey[i]==key){
                timevalue = objectValue[i];
            }
        }
    }

	<%
	List list = formviewService.findFormviewfieldByViewid(viewid);
	Map map = new HashMap();
	for (int i = 0; i < list.size(); i++) {
		Formviewfield formviewfield =(Formviewfield) list.get(i);
		if("$currenttime$".equals(formviewfield.getFormula()==null?"":formviewfield.getFormula().trim())){
    %>
        if(document.getElementById("<%=formviewfield.getFieldid()%>")!=null){
            objectKey[<%=i%>]="<%=formviewfield.getFieldid()%>";
            objectValue[<%=i%>]=document.getElementById("<%=formviewfield.getFieldid()%>").value;
        }else{
            var i=0;
            while(document.getElementById("<%=formviewfield.getFieldid()%>_"+i)!=null){
                objectKey[<%=i++%>]="<%=formviewfield.getFieldid()%>_"+i;
                objectValue[<%=i++%>]=document.getElementById("<%=formviewfield.getFieldid()%>_"+i).value;
                i++;
            }
        }
    <%
        }
	}%>


 	function onPopup(url){
		var id=showDialog("${ctx}"+url);
	}
function onEdit(){
    window.location="${ctx}/form/formprocess.jsp?editmode=1&directoryid=<%=directoryid%>&processid=<%=id%>";
}
function onDelete(id) {
        yes('<%=I18n.getText("deleteConfirm")%>', function() {
            Ext.Ajax.request({
                url:'${ctx}/formdata.do?action=delete',
                sync:true,
                params:{processid:'<%=id%>'},
                success: function(res) {
                    var result = res.responseText;
                    if (result == 'success') {
                        if(parent.contentPanel)
                        try {
                            var tabpanel = parent.contentPanel;
                            tabpanel.remove(tabpanel.getActiveTab());
                        } catch (e) {
                        }
                        try {
                            top.commonDialog.close();
                        } catch (e) {
                        }
                        try {
                            parent.dg.opt.onCancel();
                            parent.dg.cancel();
                        } catch (e) {
                        }

                    } else {
                        pop(result)
                    }
                }
            });
        })
    }
function onCancel(){
    if(parent.contentPanel)
    try {
        var tabpanel = parent.contentPanel;
        tabpanel.remove(tabpanel.getActiveTab());
    } catch (e) {
    }
    if(parent.Tabbar)
        try {
                var tabbar = parent.Tabbar;
                tabbar.closeTab(tabpanel.getLayout().activeItem.id)
            } catch (e) {
            }
    try {
        top.commonDialog.close();
    } catch (e) {
    }
    try {
        parent.dg.opt.onCancel();
        parent.dg.cancel();
    } catch (e) {
    }

}
function onSubmit(issave){
  checkfields="title,"+needchecklists;
  checkmessage="<%=I18n.getText("mustfill")%>";
	onCal();

  var needcheck = 0;
  if(issave == 0){

  }else
   		needcheck = 1;

  if(needcheck == 1){
	  if(checkForm(mainForm,checkfields,checkmessage)){
          $("input[name^='checknode_']").each(function() {
              el = this.parentNode;
              while (el && el.tagName != "TR") {
                  el = el.parentNode;

              }
              this.nextSibling.value = el.rowIndex;
          })
            <%if(!StringUtil.isEmpty(directoryfield)){%>
          if(document.getElementById('<%=directoryfield%>'))
            document.getElementById('dowid').value=document.getElementById('<%=directoryfield%>').value;
            <%}%>

    for(var num=0;num<objectKey.length;num++){
        if(objectKey[num]!=""&&objectKey[num]!=null){
            getMapValue(objectKey[num]);
            if(timevalue==document.getElementById(objectKey[num]).value){
                document.getElementById(objectKey[num]).value="$currenttime$";
            }
        }
    }
               document.mainForm.submit();
               <%if(!StringUtil.null2String(reportid).equals("")){%>
               publish('refreshstore','<%=reportid%>') ;
              <%}%>
	  }
  }
}
 function onSubmitNew(issave)
 {
  checkfields="title,"+needchecklists;
  checkmessage="<%=I18n.getText("mustfill")%>";
  document.getElementById('submitnew').value='submitnew';
	onCal();
  var needcheck = 0;
  if(issave == 0){

  }else
   		needcheck = 1;

  if(needcheck == 1){
	  if(checkForm(mainForm,checkfields,checkmessage)){
            <%if(!StringUtil.isEmpty(directoryfield)){%>
          if(document.getElementById('<%=directoryfield%>'))
            document.getElementById('dowid').value=document.getElementById('<%=directoryfield%>').value;
            <%}%>
	   		document.mainForm.submit();
            <%if(!StringUtil.null2String(reportid).equals("")){%>
               publish('refreshstore','<%=reportid%>') ;
              <%}%>
	  }
  }
 }
 function checkFileSize(filepath,maxSize){
    var size=getFileSize(filepath);
    if(size>maxSize)
    return false;
    return true;
}
function getFileSize(filepath){
 if(filepath=='')
 {
 return null;
 }
 try
 {
 filecheck.FilePath=filepath;
 var size=filecheck.getFileSize()/(1024*1024);
     return size;
 }
 catch(e)
 {
 alert(e);
 return null;
 }
 return null;
 }
 </script>
<script src='${ctx}/dwr/interface/DirectoryExcelService.js'></script>
<script type="text/javascript">

    var total = 0;
    var currentCount = 0;
    var lostnum = 0;
    var refresstimer;
    var pbar1;
    var isfinish = "0";
    var dlg0;

    Ext.onReady(function () {
        //==== Progress bar1  ====
        pbar1 = new Ext.ProgressBar({
            text:'0%'
        });


        dlg0 = new Ext.Window({
            layout:'border',
            closable:false,
            plain:true,
            modal:true,
            width:400,
            height:300,
            buttons:[
                {
                    text:'<%=I18n.getText("import")%>',
                    handler:function () {
                        importRecords(this);

                    }

                },
                {
                    text:'<%=I18n.getText("close")%>',
                    handler:function () {
                        dlg0.hide();
                        window.location.reload();
                    }

                }
            ],
            items:[
                {
                    id:'dlgpanel',
                    region:'center',
                    contentEl:'dlgdiv',
                    autoScroll:true
                }
            ]
        });
        dlg0.render(Ext.getBody());
        $('#dlgdiv').show();
    })
    var Runner = function () {
        var f = function (pbar, count, cb) {

            return function () {
                doRefresh();
                if (isfinish == "1") {
                    clearInterval(refresstimer);
                    cb();
                } else {
                    var i = currentCount / count;
                    pbar.updateProgress(i, Math.round(100 * i) + '%');
                }
            };
        };
        return {
            run:function (pbar, count, cb) {
                var ms = 5000 / count;
                try {
                    refresstimer = setInterval(f(pbar, count, cb), 2);
                } catch (e) {
                }
            }
        }
    }();

    var path = "";
    var btn;
    var excelformid;
    function importExcel(formid) {
            excelformid = formid;
            dlg0.show();
        }
    function downloadLostRecord() {
        window.open("${ctx}/excelupload.do?action=download&path=" + path);
    }
    function importRecords(b) {
        if ($('#processid').val() == null || $('#processid').val() == '') {
            alert("请先保存表单数据");
            return;
        }
        btn = b;
        isfinish = "0";
        document.getElementById("curmsg").style.display = "block";
        document.getElementById("endmsg").style.display = "none";
        if (document.excelForm.path.value == "" || document.excelForm.path.value == null) {
            alert("你还没有选择需要导入的excel文档");
            return;
        }
        document.excelForm.action = "${ctx}/excelopt.do?action=excelupload";
        document.excelForm.submit();
        btn.disable();
        getPath();
    }
    function getPath() {
        path = frames["uploadframe"].document.getElementById("pathtext").value;

        if (path == "" || path == null) {
            setTimeout("getPath()", 1000);
        } else {
            total = 0;
            currentCount = 0;
            Ext.fly('p1').setDisplayed(true);
            Ext.fly('p1text').update('');
            if (!pbar1.rendered) {
                pbar1.render('p1');
            } else {
                pbar1.text = '0%';
                pbar1.show();
            }
            showprocessbar();
            if (total == -1) {
                pbar1.reset(true);
                btn.enable();
                Ext.fly('p1text').update('请等待先前的任务完成').show();
                return;
            }
            if (total == 0) {
                btn.enable();
                pbar1.reset(true);

                var progressBarhome = document.getElementById("progressBarhome");
                var progressBar = document.getElementById("progressBar");
                progressBarhome.appendChild(progressBar);

                document.getElementById("importMessage").style.display = "none";
                Ext.fly('p1text').update('没有记录导入').show();
                return;
            }
            Runner.run(pbar1, total, function () {
                pbar1.reset(true);
                document.getElementById("successRecord").innerText = "点击查看";
                document.getElementById("endmsg").innerText = "操作完成!";
                btn.enable();
            });
        }
    }
    function doImportOpt() {
        dwr.engine.setAsync(false);
        DirectoryExcelService.inputExcelDetail($('#processid').val(), path, excelformid, returnTotal);
        dwr.engine.setAsync(true);
    }

    function returnTotal(o) {
        total = o;
        document.getElementById("totalNum").innerText = total;
    }
    function returnCurrentCount(o) {
        var obj = eval('(' + o + ')');
        ;

        var successNum = obj.successNum;
        lostnum = parseInt(obj.lostNum);

        var curNum = parseInt(successNum) + lostnum
        document.getElementById("curnum").innerText = curNum;

        document.getElementById("successNum").innerText = parseInt(successNum);
        document.getElementById("lostNum").innerText = lostnum;

        currentCount = curNum;
        isfinish = obj.isfinish;
        if (curNum == total) {
            document.getElementById("curmsg").style.display = "none";
            document.getElementById("endmsg").style.display = "block";
            if (isfinish != "1") {
                document.getElementById("endmsg").innerText = "数据导入操作已完成,正在生成错误信息文件,请稍候...";
            }
        }
    }
    function doRefresh() {
        DirectoryExcelService.getInPutCurrentCount(returnCurrentCount);
    }

    function showprocessbar() {
        doImportOpt();
    }
</script>



